package com.cloud.basic.Optional;

import java.util.Optional;

/**
 * @program: basic
 * @description: optionalTest
 * @author: Cloud
 * @create: 2021/11/8 09:08:10
 */
public class optionalTest {

    public static String getOptionals(OptionalObj optionalObj){
        if (optionalObj.getOptionalObj1() != null) {
            OptionalObj1 optionalObj1 = optionalObj.getOptionalObj1();
            if (optionalObj1 != null) {
                String name = optionalObj1.getName();
                if (name != null) {
                    optionalObj1.setName("宁瑶");
                    System.out.println("optionalObj1.getName() = " + optionalObj1.getName());
                }
            }
        }
        return "对象为空！";
    }

    public static String getOptionals1(OptionalObj optionalObj) throws Exception {
        return Optional.ofNullable(optionalObj)
                .map(optionalObj1 -> optionalObj.getOptionalObj1())
                .map(optionalObj11 -> optionalObj11.getName())
                .orElseThrow(()->new Exception("对象为空！"));
    }

    public static String getOptionals2(OptionalObj optionalObj){
        OptionalObj1 optionalObj1 = optionalObj.getOptionalObj1();
        if (optionalObj1 != null) {
            if (optionalObj1.getName().equals("陈十一")) return optionalObj1.getName();
        } else {
            optionalObj1 = new OptionalObj1();
            optionalObj1.setName("阿良");
        }
        return optionalObj1.getName();
    }

    public static OptionalObj1 getOptionals3(OptionalObj optionalObj){
        return Optional.ofNullable(optionalObj)
                .map(optionalObj1 -> optionalObj1.getOptionalObj1())
                .filter(optionalObj11 -> optionalObj11.getName().equals("陈十一"))
                .orElseGet(() ->{
                    OptionalObj1 optionalObj1 = new OptionalObj1();
                    optionalObj1.setName("阿良");
                    return optionalObj1;
                });

    }

    public static void main(String[] args) throws Exception {
        OptionalObj optionalObj = new OptionalObj();
        System.out.println("getOptionals() = " + getOptionals(optionalObj));
        System.out.println("getOptionals3(optionalObj) = " + getOptionals3(optionalObj).getName());
        System.out.println("getOptionals2() = " + getOptionals2(optionalObj));

    }
}
